package com.ikkong.biz.meta.intercept;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.Sets;
import com.ikkong.biz.model.Teacher;
import com.ikkong.core.aop.AopContext;
import com.ikkong.core.constant.ConstShiro;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.meta.PageIntercept;
import com.ikkong.core.toolbox.Conver;
import com.ikkong.core.toolbox.kit.CollectionKit;
import com.ikkong.core.toolbox.support.BladePage;
import com.ikkong.system.model.Dept;

public class TeacherIntercept extends PageIntercept {
	public void queryBefore(AopContext ac) {
		if (ShiroKit.lacksRole(ConstShiro.ADMINISTRATOR)) {
			Teacher t = ShiroKit.getTeacher();
			String depts = JStrKit.removeWrapWithDelimiter(t.getDepts());
			String condition = "and is_str_in_dept(depts,get_dept_childrens('"+depts+"'))";
			ac.setCondition(condition);
		}
	}

	/**
	 * 查询后附加字典项
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void queryAfter(AopContext ac) {
		BladePage<Map<String, Object>> page = (BladePage<Map<String, Object>>) ac.getObject();
		List<Map<String, Object>> list = page.getRows();
        for (Map<String,Object> m: list
             ) {
            String depts = Conver.toStr(m.get("depts"),"");
            if (JStrKit.notBlank(depts)){
                String[] ids = JStrKit.removeWrapWithDelimiter(depts).split(",");
                Set<String> set = Sets.newHashSet();
                for (String s:ids
                     ) {
                    Dept d = Blade.create(Dept.class).findById(s);
                    set.add(d.getSimplename());
                }
                m.put("dept_names", CollectionKit.join(set,","));
            }
        }
    }

}
